package UDP;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;

public class UDPClient
{
    public static void main (String[] args)
    {
        //创建客户端发送对象需要的DatagramSocket对象，要给定端口，客户端和服务端不一个设备端口可以一样，但是是同一个设备端口不能一样
        try(DatagramSocket datagramSocket = new DatagramSocket(8888);
            Scanner scan = new Scanner(System.in);
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
//            DataOutputStream dataOutputStream = new DataOutputStream(byteArrayOutputStream)
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream)
            )
        {
            System.out.println("请输入Person类的姓名和年龄");
            String Name = scan.next();
            int age = scan.nextInt();
            
            Person person = new Person();
            person.setName(Name);
            person.setAge(age);
            
            objectOutputStream.writeObject(person);
            byte[] bytes = byteArrayOutputStream.toByteArray();
            
//            //传递基本数据类型
//            int i = scan.nextInt();
//            //进行基本数据类型转换
//            dataOutputStream.writeInt(i);
//            byte[] bytes = byteArrayOutputStream.toByteArray();
//
//            String temp = scan.next();
//            //数据需要进行类型转换，转换为字节数组数据类型
//            byte[] bytes = temp.getBytes(StandardCharsets.UTF_8);
            
            //输入IP和端口号
            System.out.println("请输入服务端IP和端口号：");
            String IP = scan.next();
            int PORT = scan.nextInt();
//            String[] split = IP.split(" ");
            
//          //创建数据报包对象
//            DatagramPacket datagramPacket = new DatagramPacket(bytes,
//                                                               bytes.length,
//                                                               InetAddress.getByName(split[0]),
//                                                               Integer.parseInt(split[1])
//            );
            
            DatagramPacket datagramPacket = new DatagramPacket(bytes,
                                                               bytes.length,
                                                               InetAddress.getByName(IP),
                                                               PORT
            );
            
            //发送给服务端
            datagramSocket.send(datagramPacket);
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
    }
}
